package cn.hyman.durable;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

import static cn.hyman.JmsProduce_topic.TOPIC_NAME;

public class JmsConsumer_topic {
    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("我是持久化一号消费者！");
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.2.165:61616");
        Connection connection = connectionFactory.createConnection();
        // 设置客户端ID。向MQ服务器注册自己的名称 必须的不然会报
        // You cannot create a durable subscriber without specifying a unique clientID on a Connection
        connection.setClientID("订阅者NO.1");
        connection.start();
        final Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        // 第五步：使用Session对象创建一个Destination对象。和发送端保持一致queue，并且队列的名称一致。
        Topic topic = session.createTopic(TOPIC_NAME);
        // 创建一个topic订阅者对象。一参是topic，二参是订阅者名称
        TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic, "remark...");
        for (int i = 0; i < 3; i++) {
            Message message = topicSubscriber.receive(4000L);
            if (message != null) {
                System.out.println("消费者得到消息 - >" + message);
            }
        }
        //等待键盘输入，这句代码我不理解
        System.in.read();
        // 第九步：关闭资源
        session.close();
        connection.close();
    }
}
